import 'package:flutter/material.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/models/evaluation/linguisticKnowledgeResult.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/grids/evaluationLinguisticSkillProgressDataGrid.dart';
import 'package:syncfusion_flutter_gauges/gauges.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:get/get.dart';
import 'package:syncfusion_flutter_treemap/treemap.dart';
import '../../themes/appTheme.dart';

class EvaluationLinguisticTreeMap extends StatefulWidget {
  @override
  State<EvaluationLinguisticTreeMap> createState() =>
      _EvaluationLinguisticTreeMapState();
}

class _EvaluationLinguisticTreeMapState
    extends State<EvaluationLinguisticTreeMap> {
  final box = Hive.box('appconfig');
  final EvaluationController _evaluationController = Get.find();
  String _classId = '';
  bool isTeacher = false;

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;

    if (isTeacher) {
      _classId = box.get(CacheManagerKey['currentclass'].toString());
    } else {
      _classId = '';
    }

    Future.delayed(Duration(milliseconds: 200), (() {
      _evaluationController.fetchEvaluationLinguisticKnowledgesData(
          _classId, _evaluationController.currentLevel.value.toString(), '');
    }));

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build evaluation linguistic treemap');
    box.put('SkillType', 'Linguistics');
    /////tab_LINGUISTICS页面////////
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: Column(
          children: [
            Expanded(
              child: _evaluationController.obx(
                (data) => SfTreemap(
                  dataCount: Constants.evaluationLinguisticTypes.length,
                  weightValueMapper: (int index) {
                    return 1;
                    // return Constants.evaluationLinguisticTypes[index].weight!
                    //     .toDouble();
                  },
                  levels: [
                    //////////////单个仪表区块/////////////////////
                    TreemapLevel(
                        color: Get.isDarkMode
                            ? AppTheme.colors.darkTheme2
                            : Colors.white.withOpacity(0.4),
                        //padding: EdgeInsets.fromLTRB(0.0, 1.0, 3.0, 6.0),
                        border: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3.0),
                        ),
                        groupMapper: (int index) {
                          return Constants
                              .evaluationLinguisticTypes[index].skill;
                        },
                        labelBuilder: (BuildContext context, TreemapTile tile) {
                          if (_evaluationController
                                      .evaluationLinguisticKnowledgeData
                                      .value
                                      .grammar !=
                                  null &&
                              tile.group == 'Grammar') {
                            return _buildLinguisticGauge(
                                tile.group,
                                _evaluationController
                                    .evaluationLinguisticKnowledgeData
                                    .value
                                    .grammar as TotalProgress,
                                isTeacher);
                          } else if (_evaluationController
                                      .evaluationLinguisticKnowledgeData
                                      .value
                                      .phrase !=
                                  null &&
                              tile.group == 'Words') {
                            return _buildLinguisticGauge(
                                tile.group,
                                _evaluationController
                                    .evaluationLinguisticKnowledgeData
                                    .value
                                    .phrase as TotalProgress,
                                isTeacher);
                          } else if (_evaluationController
                                      .evaluationLinguisticKnowledgeData
                                      .value
                                      .syllable !=
                                  null &&
                              tile.group == 'Syllables') {
                            return _buildLinguisticGauge(
                                tile.group,
                                _evaluationController
                                    .evaluationLinguisticKnowledgeData
                                    .value
                                    .syllable as TotalProgress,
                                isTeacher);
                          } else if (_evaluationController
                                      .evaluationLinguisticKnowledgeData
                                      .value
                                      .word !=
                                  null &&
                              tile.group == 'Characters') {
                            TotalProgress wp = TotalProgress();
                            wp.progress = _evaluationController
                                .evaluationLinguisticKnowledgeData
                                .value
                                .word
                                ?.progress;
                            wp.total = _evaluationController
                                .evaluationLinguisticKnowledgeData
                                .value
                                .word
                                ?.total;
                            return _buildLinguisticGauge(
                                tile.group, wp, isTeacher);
                          } else {
                            return Padding(
                              padding: const EdgeInsets.all(4.0),
                              child: Text(''),
                            );
                          }
                        }),
                  ],
                ),
                onEmpty: Text('Data not available ...'.tr),
                // onLoading: Center(
                //     child: CircularProgressIndicator(
                //   backgroundColor: Get.theme.primaryColorDark,
                //   strokeWidth: 9.0,
                // )),
              ),
            ),
          ],
        ),
      ),
    );
  }

  GestureDetector _buildLinguisticGauge(
      String skillType, TotalProgress progressData, bool isTeacher) {
    var evaluationSkillType = Constants.evaluationLinguisticTypes
        .where((element) => element.skill == skillType)
        .first;
    String _cstring = evaluationSkillType.color.toString();
    double _progress = 0;

    if (progressData.progress == null ||
        progressData.progress == 0 ||
        progressData.total == null ||
        progressData.total == 0) {
      _progress = 0;
    } else {
      _progress = (progressData.progress! / progressData.total!) * 100;
    }

    return GestureDetector(
      onTap: () {
        if (isTeacher) {
          Get.to(() =>
              EvaluationLinguisticSkillProgressDataGrid(skillType: skillType));
        }
      },
      child: SfRadialGauge(
        enableLoadingAnimation: true,
        animationDuration: 2500,
        axes: <RadialAxis>[
          RadialAxis(
              axisLineStyle: const AxisLineStyle(
                  thicknessUnit: GaugeSizeUnit.factor, thickness: 0.2),
              radiusFactor: 0.8,
              showTicks: false,
              interval: 10,
              showFirstLabel: false,
              showLastLabel: true,
              maximum: 100,
              axisLabelStyle: const GaugeTextStyle(),
              annotations: <GaugeAnnotation>[
                GaugeAnnotation(
                    angle: 180,
                    widget: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        //Image.asset(_image),
                        Text(
                          '${_progress.toInt().toString()}% \n${skillType.replaceAll('Characters', 'Handwriting Characters')}',
                          style: TextStyle(
                              color: Get.isDarkMode
                                  ? Get.theme.primaryColorDark
                                  : Colors.blueGrey,
                              fontFamily: 'Times',
                              fontSize: 14.0,
                              fontWeight: FontWeight.w400,
                              fontStyle: FontStyle.italic),
                        ),
                      ],
                    )),
              ],
              pointers: <GaugePointer>[
                NeedlePointer(
                    enableAnimation: true,
                    gradient: const LinearGradient(colors: <Color>[
                      Color.fromRGBO(203, 126, 223, 0),
                      Color(0xffd8ffff)
                    ], stops: <double>[
                      0.25,
                      0.75
                    ], begin: Alignment.bottomCenter, end: Alignment.topCenter),
                    animationType: AnimationType.easeOutBack,
                    value: _progress,
                    animationDuration: 1300,
                    needleStartWidth: 2,
                    needleEndWidth: 4,
                    needleLength: 0.7,
                    knobStyle: const KnobStyle(
                      knobRadius: 0,
                    )),
                RangePointer(
                    value: _progress,
                    width: 0.20,
                    sizeUnit: GaugeSizeUnit.factor,
                    color: hexStringToHexInt(_cstring),
                    animationDuration: 1300,
                    animationType: AnimationType.easeOutBack,
                    enableAnimation: true)
              ])
        ],
      ),
    );
  }
}
